var express = require('express');
var router = express.Router();
var userdao = require('../dao/userdao');
var uuid = require('node-uuid');
/* GET users listing. */
router.get('/', function (req, res, next) {
  userdao.getList().then(function (result) {
    res.render('userlist', { data: result });
  }, function (data_error) {
    console.error(data_error);
    res.render('userlist', { data: [] });
  });
});

router.get('/useradd', function (req, res, next) {
  var clientid = req.body.clientid || uuid.v4().replace(new RegExp('-', 'gm'), '');
  res.cookie('clientid', clientid, { maxAge: 1000 * 60 * 60 * 24 * 30 });
  res.render('useradd', { clientid: clientid });
});

router.get('/member', function (req, res, next) {
  var uid = req.query['uid'];
  userdao.getMember(uid).then(function (result) {
    res.render('member', { data: result[0] });
  }, function (data_error) {
    console.error(data_error);
    res.render('member', { data: [] });
  });
});

router.post('/add', function (req, res, next) {
  var user = req.body;
  //console.log(user);
  userdao.insert(user).then(function (result) {
    console.log(result);
    res.send({ result: 'success' });
  }, function (data_error) {
    console.error(data_error);
    res.send({ result: 'error' });

  });
});

router.post('/statusChange', function (req, res, next) {
  var status = req.body.status;
  var uid = req.body.uid;
  status = (status == '1' ? '0' : '1');//切换状态
  userdao.statusChange(uid, status).then(function (result) {
    console.log(result);
    res.send({ result: 'success' });
  }, function (data_error) {
    console.error(data_error);
    res.send({ result: 'error' });
  });
});

router.post('/resetpassword', function (req, res, next) {
  var uid = req.body.uid;
  userdao.resetPassword(uid).then(function (result) {
    console.log(result);
    res.send({ result: 'success' });
  }, function (data_error) {
    console.error(data_error);
    res.send({ result: 'error' });
  });
});

router.post('/changepassword', function (req, res, next) {
  var user = req.body;
  //console.log(user);
  userdao.changepassword(user).then(function (result) {
    console.log(result);
    res.send({ result: 'success' });
  }, function (data_error) {
    console.error(data_error);
    res.send({ result: 'error' });

  });
});
module.exports = router;
